package com.stark.commons.spring.core.boot.config;

import java.io.IOException;
import java.util.Properties;

import org.elasticsearch.client.transport.TransportClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.stark.commons.spring.core.boot.properties.XPackElasticsearchProperties;
import com.stark.commons.spring.core.support.elasticsearch.xpack.XPackTransportClientFactoryBean;

/**
 * <code>Elasticsearch</code> 整合 <code>X-Pack</code> 配置项。
 * @author Ben
 * @since 1.0.0
 * @version 1.0.0
 */
@Configuration
@ConditionalOnClass(name = {
		"org.elasticsearch.client.Client",
		"org.elasticsearch.xpack.client.PreBuiltXPackTransportClient"
})
@ConditionalOnProperty(prefix = "spring.data.elasticsearch.xpack", name = "security-transport-ssl-enabled", havingValue = "true")
@AutoConfigureBefore(name = "org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchAutoConfiguration")
@EnableConfigurationProperties(XPackElasticsearchProperties.class)
public class XPackElasticsearchAutoConfig {
	
	@Autowired
	private XPackElasticsearchProperties xpackElasticsearchProperties;
	@Autowired
	private ElasticsearchProperties elasticsearchProperties;

	@Bean
	public TransportClient elasticsearchClient() throws Exception {
		XPackTransportClientFactoryBean factory = new XPackTransportClientFactoryBean();
		factory.setClusterNodes(xpackElasticsearchProperties.getClusterNodes());
		factory.setProperties(createProperties());
		factory.afterPropertiesSet();
		return factory.getObject();
	}
	
	private Properties createProperties() throws IOException {
		Properties properties = new Properties();
		properties.putAll(elasticsearchProperties.getProperties());
		properties.put("cluster.name", xpackElasticsearchProperties.getClusterName());
		properties.put("client.transport.sniff", xpackElasticsearchProperties.isClientTransportSniff());
		properties.put("client.transport.ignore_cluster_name", xpackElasticsearchProperties.isClientIgnoreClusterName());
		properties.put("client.transport.ping_timeout", xpackElasticsearchProperties.getClientPingTimeout());
		properties.put("client.transport.nodes_sampler_interval", xpackElasticsearchProperties.getClientNodesSamplerInterval());
		properties.putAll(xpackElasticsearchProperties.getXpack().createProperties());
		return properties;
	}
	
}
